package org.dreamwork.jasmine2.parser;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Properties;

public class CSS {
    protected String name;
    protected CSS parent;
    protected Properties attributes = new Properties ();
    protected Properties attributesIgnoreCase = new Properties ();
    protected HashMap<String, CSS> children   = new HashMap<String, CSS> ();
    protected HashMap<String, CSS> childrenIgnoreCase = new HashMap<String, CSS> ();

    public CSS (String name) {
        this.name = name;
    }

    public void addChild (CSS css) {
        children.put (css.name, css);
        childrenIgnoreCase.put (css.name.toUpperCase (), css);
    }

    public CSS getChild (String name) {
        CSS css = childrenIgnoreCase.get (name.toUpperCase ());
        if (css != null) return css;
        if (name.indexOf (".") > 0) {
            CSS current = this;
            String[] names = name.split ("\\.");
            for (int i = 0; i < names.length; i ++) {
                String key = names [i];
                CSS next = current.childrenIgnoreCase.get (key.toUpperCase ());
                if (next != null && i != names.length - 1) current = next;
                else break;
            }
        }
        return null;
    }

    public CSS[] getChildren () {
        ArrayList<CSS> list = new ArrayList<CSS> (children.size ());
        list.addAll (children.values ());
        CSS[] child = new CSS [list.size ()];
        return list.toArray (child);
    }

    public String [] getChildNames () {
        ArrayList<String> list = new ArrayList<String> (children.size ());
        list.addAll (children.keySet ());
        String[] names = new String [list.size ()];
        return list.toArray (names);
    }

    public void setAttribute (String name, String value) {
        attributes.setProperty (name, value);
        attributesIgnoreCase.setProperty (name.toUpperCase (), value);
    }

    public String getAttribute (String name) {
        return attributesIgnoreCase.getProperty (name.toUpperCase ());
    }

    public Properties getAttributes () {
        return attributes;
    }
}